package com.canoe.text;

import com.canoe.common.CanoeException;
import com.canoe.text.common.TextOrder;
import com.canoe.text.processor.TextExtractProcessor;

import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * text指令适配器
 *
 * @author: btm
 * @time: 20:13 2020/9/22
 **/
public class TextOrderAdapter {

    private static final ConcurrentHashMap<TextOrder, AbstractTextOrderProcessor> textOrderProcessorMap = new ConcurrentHashMap<>();

    private static final ArrayList<AbstractTextOrderProcessor> textOrderProcessorList = new ArrayList<>();

    static {
        textOrderProcessorList.add(new TextExtractProcessor());
    }

    /**
     * 初始化text指令适配器饿的时候，将所有的text指令执行器注册到适配器中
     */
    public TextOrderAdapter() {
        if (0 >= textOrderProcessorMap.size()) {
            for (AbstractTextOrderProcessor textOrderProcessor : textOrderProcessorList) {
                if (Objects.nonNull(textOrderProcessor)) {
                    textOrderProcessorMap.put(textOrderProcessor.support(), textOrderProcessor);
                }
            }
        }
    }

    /**
     * 根据text指令获得对应的处理器
     * @param textOrder text指令{@link TextOrder}
     * @returnt text指令处理器
     */
    public AbstractTextOrderProcessor getProcessor(TextOrder textOrder) {
        AbstractTextOrderProcessor processor = textOrderProcessorMap.get(textOrder);
        if (Objects.nonNull(processor)) {
            return processor;
        }
        throw new CanoeException("There is not a processor for text order: "+textOrder.getOrderName());
    }
}
